package com.eims.sls_app.ui;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.toolbox.RequestParams;
import com.eims.sls_app.dataaccess.LotteryContent;
import com.eims.sls_app.dataaccess.Schemes;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.ui.adapter.MyInfoListAdapter;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.LotteryUtils;
import com.eims.sls_app.view.ConfirmDialog;
import com.eims.sls_app.view.MyInfoListVo;
import com.eims.sls_app.view.MyToast;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import bls.juejin.cn.R;
import progressBar.ProgressDialogBar;

public class MyinfoListActivity extends Activity implements OnClickListener {

	private ListView listview;
	private MyInfoListAdapter adapter;

	private ImageButton ibBack;
	private TextView tvClear;
	private String opt, info, time, imei, crc;
	private String auth;
	private GetinfoMyHandler getinfoMyHandler;
	private static final String TAG = "MyinfoListActivity";

	private List<MyInfoListVo> listMyinfo;

	Schemes scheme;
	private getMyHandler getMyHandler;
	private String getauth, getinfo, gettime, getimei, getcrc, getkey; // 格式化后的参数
	private String getopt = "46"; // 格式化后的 opt
	private String id, sumid, isopen, circleId;
	private boolean isJoin = true;
	private int clearPosition;
	private ConfirmDialog dialog;// 提示框

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.my_info_list_zq_circle);
		getinfoMyHandler = new GetinfoMyHandler();
		getMyHandler = new getMyHandler();
		App.activityS.add(this);

		findView();
	}

	private void findView() {

		listview = (ListView) findViewById(R.id.listview);

		ibBack = (ImageButton) findViewById(R.id.btn_back);
		tvClear = (TextView) findViewById(R.id.tv_clear);

		ibBack.setOnClickListener(this);
		tvClear.setOnClickListener(this);
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				// TODO Auto-generated method stub
				// Toast.makeText(MyinfoListActivity.this, position + "",
				// Toast.LENGTH_SHORT).show();
				clearPosition = position;
				circleId = listMyinfo.get(position).getId() + "";
				id = listMyinfo.get(position).getUid() + "";
				sumid = listMyinfo.get(position).getSchemeid() + "";
				ProgressDialogBar.startProgress(MyinfoListActivity.this, "xxs", true);

				if (!listMyinfo.get(position).getIsopen().equals("ture")) {
					isopen = "0";
					// pd = BaseHelper.showProgress(context, "", "加载中...", true, false);

					// Toast.makeText(context, "该方案内容开奖后可见！", Toast.LENGTH_SHORT).show();
					GetMyAsynTask getMyAsynTask = new GetMyAsynTask();
					getMyAsynTask.execute();

				} else {
					isopen = "1";

					GetMyAsynTask getMyAsynTask = new GetMyAsynTask();
					getMyAsynTask.execute();
				}
			}
		});
		getInfoMyview();
		dialog = new ConfirmDialog(this, R.style.dialog);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;
		case R.id.tv_clear:
			if (!App.getInfoNum.equals("0")) {
				dialog.show();
				dialog.setDialogContent("您确认删除全部提示信息,您的信息将不会被保存？");
				dialog.setDialogResultListener(new ConfirmDialog.DialogResultListener() {
					@Override
					public void getResult(int resultCode) {
						// TODO Auto-generated method stub
						if (1 == resultCode) {// 确定

							clearInfoMyview();
						}
					}
				});
			} else {
				MyToast.getToast(MyinfoListActivity.this, "沒有信息可删除！").show();
			}

			break;

		default:
			break;
		}
	}

	private void clearInfoMyview() {
		if (App.user != null) {
			ProgressDialogBar.startProgress(MyinfoListActivity.this, "xxs", true);
			clearMyAsynTask asynTask = new clearMyAsynTask();
			asynTask.execute();
		}

	}

	private void getInfoMyview() {
		if (App.user != null) {
			ProgressDialogBar.startProgress(MyinfoListActivity.this, "xxs", true);
			listMyinfo = new ArrayList<MyInfoListVo>();
			GetinfoMyAsynTask getinfoMyAsynTask = new GetinfoMyAsynTask();
			getinfoMyAsynTask.execute();
		}

	}

	class GetinfoMyAsynTask extends AsyncTask<Integer, Integer, String> {

		String error = "0";

		@Override
		protected String doInBackground(Integer... params) {

			opt = "106";
			time = RspBodyBaseBean.getTime();
			imei = RspBodyBaseBean.getIMEI(MyinfoListActivity.this);

			info = "";
			String key = App.key;
			crc = RspBodyBaseBean.getCrc(time, imei, key, info, App.user.getUid());
			auth = RspBodyBaseBean.getAuth(crc, time, imei, App.user.getUid());
			String[] values = { opt, auth, info };
			Log.i(TAG, "xiadan" + RequestParams.convertParams(MyinfoListActivity.this, opt, info));
			String result = HttpUtils.doPost(App.names, values, App.path);
			Log.e(TAG, "xiadan-----" + result);
			if (result.equals("[]") || result.equals("")) {
				error = "-1";
				return error;
			}
			listMyinfo.clear();

			try {
				JSONArray arr = new JSONArray(result);

				for (int i = 0; i < arr.length(); i++) {
					MyInfoListVo infoListVo = new MyInfoListVo();
					JSONObject items2 = arr.getJSONObject(i);

					infoListVo.setId(items2.getString("id"));
					infoListVo.setName(items2.getString("Name"));
					infoListVo.setContext(items2.getString("context"));
					infoListVo.setDatetime(items2.getString("datetime"));
					infoListVo.setCid(items2.getString("cid"));
					infoListVo.setDetail(items2.getString("detail"));
					infoListVo.setSchemeid(items2.getString("schemeid"));
					infoListVo.setHeadurl(items2.getString("Headurl"));
					infoListVo.setNid(items2.getString("nid"));
					infoListVo.setIsopen(items2.getString("isopen"));
					infoListVo.setUid(items2.getString("uid"));
					listMyinfo.add(infoListVo);

				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				error = "-1";
				e.printStackTrace();
			}

			return error;
		}

		@Override
		protected void onPostExecute(String result) {
			getinfoMyHandler.sendEmptyMessage(Integer.parseInt(result));
			super.onPostExecute(result);
		}
	}

	@SuppressLint("HandlerLeak")
	class GetinfoMyHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case -1:
				ProgressDialogBar.stopProgress();
				MyToast.getToast(MyinfoListActivity.this, "沒有评论信息！").show();
				break;
			case 0:
				ProgressDialogBar.stopProgress();
				adapter = new MyInfoListAdapter(MyinfoListActivity.this, listMyinfo);
				listview.setAdapter(adapter);
				break;
			case 5:

				ProgressDialogBar.stopProgress();

				App.getInfoNum = Integer.parseInt(App.getInfoNum) - 1 + "";
				listMyinfo.remove(clearPosition);
				// adapter = new MyInfoListAdapter(MyinfoListActivity.this, listMyinfo);
				// listview.setAdapter(adapter);
				adapter.setInfoListVos(listMyinfo);
				adapter.notifyDataSetInvalidated();

				Intent intent_info;
				if ("72".equals(scheme.getLotteryID()) || "73".equals(scheme.getLotteryID())
						|| "45".equals(scheme.getLotteryID())) {

					intent_info = new Intent(MyinfoListActivity.this, MyCommonLotteryInfo_jc_other.class);
					App.scheme = scheme;
					intent_info.putExtra("scheme", scheme);
					intent_info.putExtra("id", id);
					intent_info.putExtra("isopen", isopen);

				} else {
					intent_info = new Intent(MyinfoListActivity.this, MyCommonLotteryInfo_other.class);
					App.scheme = scheme;
					intent_info.putExtra("scheme", scheme);
					intent_info.putExtra("id", id);
				}
				MyinfoListActivity.this.startActivity(intent_info);
				break;
			case -5:
				ProgressDialogBar.stopProgress();
				MyToast.getToast(MyinfoListActivity.this, "刪除失败！").show();
				break;
			case 10:
				ProgressDialogBar.stopProgress();
				MyToast.getToast(MyinfoListActivity.this, "删除完成！").show();
				App.getInfoNum = "0";
				listMyinfo.clear();
				adapter = new MyInfoListAdapter(MyinfoListActivity.this, listMyinfo);
				listview.setAdapter(adapter);

				break;
			case -10:
				ProgressDialogBar.stopProgress();
				MyToast.getToast(MyinfoListActivity.this, "刪除失败！").show();
				break;
			default:

				break;
			}
			super.handleMessage(msg);
		}
	}

	/**
	 * 进行页面刷新
	 */
	@SuppressLint("HandlerLeak")
	class getMyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {

			ProgressDialogBar.stopProgress();
			switch (msg.what) {
			case 0:

				clearByidMyAsynTask asynTask = new clearByidMyAsynTask();
				asynTask.execute();

				break;
			default:
				break;
			case -1:
				MyToast.getToast(MyinfoListActivity.this, "没有数据").show();
				break;
			case -500:
				MyToast.getToast(MyinfoListActivity.this, "连接超时").show();
				break;
			}
			super.handleMessage(msg);
		}
	}

	/*** 异步任务 用来后台获取数据 */
	class GetMyAsynTask extends AsyncTask<Void, Integer, String> {
		/**
		 * 在后台执行的程序
		 */
		@Override
		protected String doInBackground(Void... params) {
			getinfo = "{\"id\":" + sumid + "}";

			getopt = "15";
			Log.i("x", "投注接口 opt :" + getopt);
			Log.i("x", "投注方案详情  info  " + getinfo);

			// 加入验证后有问题,没有传key值
			getkey = App.key;
			getimei = RspBodyBaseBean.getTime();
			getimei = RspBodyBaseBean.getIMEI(MyinfoListActivity.this);
			;
			// Log.i("x", "投注方案详情 key " + key);
			// id = adapter.getTopicBeans().get(getInfoPosition).getUserid() + "";
			getcrc = RspBodyBaseBean.getCrc(gettime, getimei, getkey, getinfo, id);
			// Log.i("x", "投注方案详情 crc " + crc);
			getauth = RspBodyBaseBean.getAuth(getcrc, gettime, getimei, id + "");
			// Log.i("x", "投注方案详情=== auth " + auth);
			String[] values = { getopt, getauth, getinfo };
			String result = HttpUtils.doPost(App.names, values, App.path);
			Log.e(TAG, "晒单" + RequestParams.convertParamsfor(MyinfoListActivity.this, getopt, getinfo, id));
			Log.e("x", "得到投注内容   " + result);
			scheme = new Schemes();
			if ("-500".equals(result))
				return result;

			if (null == result)
				return "1";
			//
			try {

				JSONObject item = new JSONObject(result);

				if ("0".equals(item.optString("error"))) {
					String schemeList = item.optString("schemeList");

					JSONArray array = new JSONArray(schemeList);

					JSONArray jsonArray2 = new JSONArray(array.toString());

					if (jsonArray2.length() == 0)
						return "1";
					// 如果取消了 则停止
					if (this.isCancelled()) {
						Log.i("x", "取消了异步。。。。");
						return null;
					}
					JSONObject items2 = array.getJSONObject(0);
					scheme.setId(items2.optString("id"));
					// 设置订单编号
					String schemeNum = items2.optString("SchemeNumber");
					// scheme.setSchemeNumber(schemeNum.equals("")
					// ? LotteryUtils.getSchemeNum(App.lottery.getLotteryID(),
					// App.lottery.getIsuseName(),
					// circleBean.topic.get(getInfoPosition).getSchemeid())
					// : schemeNum);
					scheme.setSchemeNumber(schemeNum);
					scheme.setIsHide(items2.optInt("isHide"));
					scheme.setSecretMsg(items2.optString("secretMsg"));
					scheme.setAssureMoney(items2.optDouble("assureMoney"));
					scheme.setAssureShare(items2.optInt("assureShare"));
					scheme.setBuyed(items2.optString("buyed"));
					scheme.setInitiateName(items2.optString("initiateName"));
					scheme.setInitiateUserID(items2.optString("initiateUserID"));
					String isPurchasing = items2.optString("isPurchasing");
					if ("".equals(isPurchasing)) {
						isPurchasing = isJoin + "";
					}
					scheme.setIsPurchasing(isPurchasing);

					// // 设置订单期号
					// scheme.setIsuseID(App.lottery.getIsuseId());
					// scheme.setIsuseName(App.lottery.getIsuseName());

					scheme.setLevel(items2.optInt("level"));
					scheme.setLotteryID(items2.optString("lotteryID"));
					scheme.setLotteryName(items2.optString("lotteryName"));
					scheme.setLotteryNumber(items2.optString("lotteryNumber"));
					scheme.setMoney(items2.optInt("money"));
					scheme.setPlayTypeID(items2.optInt("playTypeID"));
					scheme.setPlayTypeName(items2.optString("playTypeName"));
					scheme.setQuashStatus(items2.optInt("quashStatus"));
					scheme.setRecordCount(items2.optInt("recordCount"));
					scheme.setSchedule(items2.optInt("schedule"));
					scheme.setSchemeBonusScale(items2.optDouble("schemeBonusScale"));
					scheme.setSchemeIsOpened(items2.optString("schemeIsOpened"));
					scheme.setSecrecyLevel(items2.optInt("secrecyLevel"));
					scheme.setSerialNumber(items2.optInt("serialNumber"));
					scheme.setShare(items2.optInt("share"));
					scheme.setShareMoney(items2.optInt("shareMoney"));
					scheme.setSurplusShare(items2.optInt("surplusShare"));
					scheme.setTitle(items2.optString("title"));
					scheme.setWinMoneyNoWithTax(items2.optDouble("winMoneyNoWithTax"));
					scheme.setWinNumber(items2.optString("winNumber"));
					// 设置订单下单时间
					scheme.setDateTime(LotteryUtils.getSchemeTime(System.currentTimeMillis()));

					scheme.setDescription(items2.optString("description"));
					scheme.setIsChase(items2.optInt("isChase"));
					scheme.setChaseTaskID(items2.optInt("chaseTaskID"));
					// 设置倍数
					scheme.setMultiple(items2.optInt("Multiple"));
					// scheme.setMultiple(20);

					scheme.setFromClient(items2.optInt("fromClient"));
					scheme.setMyBuyMoney(item.optInt("myBuyMoney") + "");
					scheme.setMyBuyShare(item.optInt("myBuyShare"));

					String schemeStatus = "待出票";
					try {
						schemeStatus = items2.getString("schemeStatus");
					} catch (JSONException e) {
						// do nothing
					}
					scheme.setSchemeStatus(schemeStatus);

					JSONArray array_contents = new JSONArray(items2.optString("buyContent"));
					List<LotteryContent> contents = new ArrayList<LotteryContent>();
					LotteryContent lotteryContent;
					for (int k = 0; k < array_contents.length(); k++) {
						lotteryContent = new LotteryContent();
						try {
							JSONArray array2 = new JSONArray(array_contents.optString(k));

							lotteryContent.setLotteryNumber(array2.getJSONObject(0).optString("lotteryNumber"));
							lotteryContent.setPlayType(array2.getJSONObject(0).optString("playType"));
							lotteryContent.setSumMoney(array2.getJSONObject(0).optString("sumMoney"));
							lotteryContent.setSumNum(array2.getJSONObject(0).optString("sumNum"));
							contents.add(lotteryContent);
						} catch (Exception e) {
							JSONObject array2 = new JSONObject(array_contents.optString(k));

							lotteryContent.setLotteryNumber(array2.optString("lotteryNumber"));
							lotteryContent.setPlayType(array2.optString("playType"));
							lotteryContent.setSumMoney(array2.optString("sumMoney"));
							lotteryContent.setSumNum(array2.optString("sumNum"));
							contents.add(lotteryContent);
						}
					}
					scheme.setBuyContent(contents);

					if (this.isCancelled()) {
						// pd.dismiss();
						Log.i("x", "取消了异步。。。。");
						return null;
					}
					return "0";
				}
			} catch (Exception e) {
				Log.i("x", "myAllLottery 错误" + e.getMessage());
			}

			return "-1";
		}

		@Override
		protected void onPostExecute(String result) {
			if (null == result)
				return;
			if ("1".equals(result)) {
				getMyHandler.sendEmptyMessage(-1);
			}
			getMyHandler.sendEmptyMessage(Integer.parseInt(result));
			super.onPostExecute(result);
		}
	}

	class clearByidMyAsynTask extends AsyncTask<Integer, Integer, String> {

		String error = "-5";

		@Override
		protected String doInBackground(Integer... params) {

			opt = "107";
			time = RspBodyBaseBean.getTime();
			imei = RspBodyBaseBean.getIMEI(MyinfoListActivity.this);

			info = circleId;
			String key = App.key;
			crc = RspBodyBaseBean.getCrc(time, imei, key, info, App.user.getUid());
			auth = RspBodyBaseBean.getAuth(crc, time, imei, App.user.getUid());
			String[] values = { opt, auth, info };
			Log.i(TAG, "xiadan" + RequestParams.convertParams(MyinfoListActivity.this, opt, info));
			String result = HttpUtils.doPost(App.names, values, App.path);
			Log.e(TAG, "xiadan-----" + result);
			if (result.equals("success")) {
				error = "5";
				return error;
			}

			return error;
		}

		@Override
		protected void onPostExecute(String result) {
			getinfoMyHandler.sendEmptyMessage(Integer.parseInt(result));
			super.onPostExecute(result);
		}

	}

	class clearMyAsynTask extends AsyncTask<Integer, Integer, String> {

		String error = "-10";

		@Override
		protected String doInBackground(Integer... params) {

			opt = "108";
			time = RspBodyBaseBean.getTime();
			imei = RspBodyBaseBean.getIMEI(MyinfoListActivity.this);

			info = "";
			String key = App.key;
			crc = RspBodyBaseBean.getCrc(time, imei, key, info, App.user.getUid());
			auth = RspBodyBaseBean.getAuth(crc, time, imei, App.user.getUid());
			String[] values = { opt, auth, info };
			Log.i(TAG, "xiadan" + RequestParams.convertParams(MyinfoListActivity.this, opt, info));
			String result = HttpUtils.doPost(App.names, values, App.path);
			Log.e(TAG, "xiadan-----" + result);
			if (result.equals("success")) {
				error = "10";
				return error;
			}

			return error;
		}

		@Override
		protected void onPostExecute(String result) {
			getinfoMyHandler.sendEmptyMessage(Integer.parseInt(result));
			super.onPostExecute(result);
		}
	}
}
